const mongoose = require('mongoose');
const {host, name, port, user, password} = require('../config/dbConfig');
const model = require('./model');
const schema = require('./schema');

const mongodbUrl = `mongodb://${user}:${password}@${host}:${port}/${name}`;
const conn = mongoose.connect(mongodbUrl,{ useNewUrlParser: true } );

// 生成model
Object.keys(schema).forEach((name) => {
    const schemaModal = new mongoose.Schema(schema[name], {timestamps: true});
    model.set(name, schemaModal);
});

mongoose.connection.on('connected', function() {
    console.log('Mongoose connected to ' + mongodbUrl);
});
mongoose.connection.on('error', function(err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
    console.log('Mongoose disconnected');
});

module.exports = conn;